package com.acceptable.qucun.generic.util;

import com.acceptable.qucun.file.mapper.FileShareItemMapper;
import com.acceptable.qucun.file.mapper.FileShareMapper;
import com.acceptable.qucun.file.mapper.TemplateFileMapper;
import com.acceptable.qucun.user.mapper.UserMapper;

import java.util.Random;

public class RandomUtil {
    private static String allNumber = "0123456789";
    private static String allSpeical = "_-";
    private static String allLetter;

    static {
        String allLower = "abcdefghijklmnopqrstuvwxyz";
        allLetter = allLower + allLower.toUpperCase();
    }

    private static String base(String all, int length){
        Random random = new Random();
        StringBuilder resStr = new StringBuilder(length);
        for (int i = 0; i < length; i++){
            resStr.append(all.charAt(random.nextInt(all.length())));
        }
        return resStr.toString();
    }

    // 生成纯数字的字符串
    public static String fullNumber(int length){
        return base(allNumber, length);
    }

    // 生成混合字符串
    public static String mixNumberLetter(int length){
        return base(allLetter + allNumber, length);
    }

    public static String shareUrlUnique(int length,
                                        FileShareMapper shareMapper){
        String shareUrl = "";
        String allChar = allNumber + allLetter + allSpeical;
        do {
            shareUrl = base(allChar, length);
        }while (shareMapper.selectByUrl(shareUrl) != null);
        return shareUrl;
    }

    public static Long shareItemIdUnique(int length,
                                         Integer userId,
                                         FileShareItemMapper shareItemMapper){
        Long itemId = null;
        do {
            itemId = Long.parseLong(fullNumber(length));
        } while (shareItemMapper.selectByShareItemId(userId, itemId) != null);
        return itemId;
    }

    public static Integer userIdUnique(int length, UserMapper userMapper){
        Integer userId = null;
        do {
            userId = Integer.parseInt(fullNumber(length));
        } while (userMapper.selectByUserId(userId) != null);
        return userId;
    }

    public static Long fileIdUnique(int length, Integer userId, TemplateFileMapper fileMapper){
        Long fileId = null;
        do {
            fileId = Long.parseLong(fullNumber(length));
        } while(fileMapper.selectByFileId(userId, fileId) != null);
        return fileId;
    }

}
